package com.duanjw.springframework.scope;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * 单例bean中获取原型bean
 *
 * @author duanjw
 */
@Component
public class SingletonWithPrototypeBean1 {
    private SingletonBean1 singletonBean1;

    public SingletonWithPrototypeBean1(SingletonBean1 singletonBean1) {
        this.singletonBean1 = singletonBean1;
    }

    public void show() {
        singletonBean1.show();
    }
}

/**
 * 单例bean
 * 不配置scope默认就是单例
 *
 * @author duanjw
 */
@Component
class SingletonBean1 implements ApplicationContextAware {
    /**
     * Spring 容器，通过容器获取bean就是
     */
    private ApplicationContext applicationContext;
    private PrototypeBean1 prototypeBean1;

    public SingletonBean1(PrototypeBean1 prototypeBean1) {
        this.prototypeBean1 = prototypeBean1;
    }

    public void show() {
        System.out.println("单例bean：（bean是同一个）" + this.hashCode());
        System.out.println("原型bean：（bean是同一个）" + prototypeBean1.hashCode());
        System.out.println("原型bean：（bean不是同一个）" + applicationContext.getBean(PrototypeBean1.class).hashCode());
        System.out.println("-----------");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

/**
 * 原型bean
 *
 * @author duanjw
 */
@Scope("prototype")
@Component
class PrototypeBean1 {

}
